// portlookup.cpp
// Given a service name, this program displays the corresponding port number.

#include <iostream>
#include <winsock2.h>
using namespace std;
#pragma comment (lib,"ws2_32.lib")

int main (int argc, char **argv)
{
	char	service[80];	// This string contains name of desired service
	struct	servent *pse;	// pointer to service information entry
	short	port;			// Port # (in Network Byte Order) of desired service

	if (argc < 2)
	{
		cout << "Please specify a service." << endl;
		return 0;
	}
	strcpy_s(service, sizeof(service), argv[1]);

	WORD wVersion = 0x0202;
	WSADATA wsaData;
	int iResult = WSAStartup(wVersion, &wsaData);  // Returns zero if successful
	if (iResult != 0) {
		cout << "Insufficient resources to startup WINSOCK." << endl;
		return 0;
	}

	port = htons( (u_short) atoi(service));	// 1st try to convert string to integer
	if (port == 0) {						// if that doesn't work, call service function
		pse = getservbyname(service,NULL);
		if (pse) {
			port = pse->s_port;
		}
		else
		{
			cout << "Invalid service request." << endl;
			return INVALID_SOCKET;
		}
	}

	cout << "Service: " << service << endl;
	cout << "Port:    " << htons(port) << endl;

}